package by.grsu.vashchilo.page.administrator;

import java.util.List;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;

import by.grsu.vashchilo.app.AirlineWebApplication;
import by.grsu.vashchilo.dao.impl.TicketDao;
import by.grsu.vashchilo.dao.impl.TicketItemDao;
import by.grsu.vashchilo.entity.Ticket;
import by.grsu.vashchilo.entity.TicketItem;


public class ListTicketPage extends WebPage{
	public ListTicketPage() {
		super();

		final TicketDao ticketDao = new TicketDao(
				AirlineWebApplication.DATA_XML_FOLDER);
		final List<Ticket> allTickets = ticketDao.getAll();

		add(new DataView<Ticket>("table-rows", new ListDataProvider<Ticket>(
				allTickets)) {
			@Override
			protected void populateItem(final Item<Ticket> item) {
				final Ticket ticket = item.getModelObject();

				item.add(new Label("id", ticket.getID()));
				item.add(new Label("tripId", ticket.getTripID()));
				item.add(new Label("seat", ticket.getSeat()));
				item.add(new Link("editLink") {
					@Override
					public void onClick() {
						setResponsePage(new TicketEditPage(ticket));
					}
				});

				item.add(new Link("deleteLink") {
					@Override
					public void onClick() {
						ticketDao.delete(ticket.getId());
						TicketItemDao ticketItemDao = new TicketItemDao(
								AirlineWebApplication.DATA_XML_FOLDER);
						List<TicketItem> listTicketItem = ticketItemDao.getAll();
						for (TicketItem b : listTicketItem) {
							if (b.getTicketid().equals(ticket.getId()))
								ticketItemDao.delete(b.getId());
						}
						setResponsePage(new ListTicketPage());
					}
				});
				item.add(new Link("deleteCopy") {
					@Override
					public void onClick() {
						TicketItemDao ticketItemDao = new TicketItemDao(
								AirlineWebApplication.DATA_XML_FOLDER);
						List<TicketItem> listTicketItem = ticketItemDao.getAll();
						for (TicketItem b : listTicketItem) {
							if (b.getTicketid().equals(ticket.getId()))
								if (b.getOwnerId() == null) {
									ticketItemDao.delete(b.getId());
									break;
								}
						}
					}
				});
				item.add(new Link("addCopy") {
					@Override
					public void onClick() {
						TicketItemDao ticketItemDao = new TicketItemDao(
								AirlineWebApplication.DATA_XML_FOLDER);
						TicketItem newTicket = new TicketItem();
						newTicket.setTicketid(ticket.getId());
						ticketItemDao.saveNew(newTicket);
					}
				});
			}
		});

		add(new Link("createLink") {
			@Override
			public void onClick() {
				setResponsePage(new TicketEditPage(new Ticket()));
			}
		});
	}
}
